<?php
/**
 * Created by : PhpStorm
 * User: 阿城 <479468212@qq.com>
 * Date: 2019/12/27
 * Time: 13:02
 */

namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\model\AdminAuthGroupAccess;
use app\admin\model\AdminAuthRule;
use app\admin\model\AdminMenu;
use app\admin\model\AdminUser;
use app\admin\model\AdminUserData;
use app\util\Tools;

class Index extends Base
{

    /**
     * @OA\Get(
     *   path="/admin/index",
     *   tags={"公共接口"},
     *   summary="后台首页",
     *   @OA\Response(response=200, description="Success")
     * )
     */
    public function index()
    {
        $this->success('后台公共首页访问成功！',['id'=>1,'username'=>'test用户','token'=>'ddfreqqreiifgjjj']);
    }

    /**
     * @OA\Get(
     *   path="/admin/Index/test",
     *   tags={"公共接口"},
     *   summary="测试接口",
     *   @OA\Response(response=200, description="Success")
     * )
     */
    public function test()
    {
        $this->success('成功');
    }

    /**
     * @OA\Post(
     *     path="/admin/Index/login",
     *     tags={"后台用户相关"},
     *     summary="用户登录",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(property="username", type="string", description="用户名"),
     *                 @OA\Property(property="password", type="string", description="密码"),
     *                 example={"username": "root", "password": "123456"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     )
     * )
     */
    public function login()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$username) {
            $this->error('缺少用户名!');
        }
        if (!$password) {
            $this->error('缺少密码!');
        } else {
            $password = Tools::userMd5($password);
        }
        $userInfo = AdminUser::where(['username' => $username, 'password' => $password])->find();
        if (!empty($userInfo)) {
            if ($userInfo['status']) {
                //更新用户数据
                $userData = $userInfo->userData;
                $data = [];
                if ($userData) {
                    $userData->login_times++;
                    $userData->last_login_ip = $this->request->ip();
                    $userData->last_login_time = time();
                    $userData->save();
                } else {
                    $data['login_times'] = 1;
                    $data['uid'] = $userInfo['id'];
                    $data['last_login_ip'] = $this->request->ip();
                    $data['last_login_time'] = time();
                    $data['head_img'] = '';
                    AdminUserData::create($data);
                    $userInfo['userData'] = $data;
                }
            } else {
                $this->error('用户已被封禁，请联系管理员');
            }
        } else {
            $this->error('用户名密码不正确');
        }
        //设置登陆缓存
        $findToken = cache('Login:' . $userInfo['id']);
        if(!empty($findToken)){
            cache('Login:' . $findToken, null);
        }
        $LoginToken = md5(uniqid() . time());
        cache('Login:' . $LoginToken, json_encode($userInfo), config('easyApi.ONLINE_TIME'));
        cache('Login:' . $userInfo['id'], $LoginToken, config('easyApi.ONLINE_TIME'));
        $userInfo['LoginToken']  = $LoginToken;
        $this->success('登录成功！',$userInfo);
    }

    /**
     * 用户登出
     * @return array
     */
    public function logout() {
        $loginToken = $this->request->header('App-Login-Token');
        cache('Login:' . $loginToken, null);
        cache('Login:' . $this->userId, null);
        $this->success('登出成功');
    }

    private function handleMenu(&$data) {
        foreach ($data as &$val){
            $val['meta'] = ['icon'=>$val['icon'],'title'=>$val['title'],'hideInMenu'=>!empty($val['hideInMenu'])?true:false];
            unset($val['id'],$val['title'],$val['hideInMenu'],$val['fid'],$val['icon']);
            if(isset($val['children'])){
                foreach ($val['children'] as $k => $v){
                    $val['meta']['access'][] = $v['url'];
                }
                $this->handleMenu($val['children']);
            }
        }
        return $data;
    }

    /**
     * 获取路由数据
     * @ param $uid
     * @ return array
     */
    public function getRoute() {
        $isSupper = Tools::isAdministrator($this->userId);
        $menuList = [];
        if ($isSupper) {
            $access = AdminMenu::field('id,path,name,0 as meta,component,title,fid,url,hide as hideInMenu,icon')->select();
            $access = Tools::buildArrFromObj($access,'id');
            $result = Tools::listToTree($access,'id','fid','children');
            $menuList = $this->handleMenu($result);
        } else {
            $groups = AdminAuthGroupAccess::where(['uid' => $this->userId])->find();
            if (isset($groups) && $groups->group_id) {
                $AuthRuleList = AdminAuthRule::whereIn('group_id', $groups->group_id)->column('url');
                $access = AdminMenu::field('id,path,name,0 as meta,component,title,fid,url,hide as hideInMenu,icon')->whereIn('url', $AuthRuleList)->select();
                $access = Tools::buildArrFromObj($access,'id');
                $result = Tools::listToTree($access,'id','fid','children');
                $menuList = $this->handleMenu($result);
            }
        }
        $this->success('成功',$menuList);
    }

}
